package com.tkp.interfaceU;

import com.tkp.config.UserTypeEnum;
import com.tkp.service.UserPayService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: duk
 * @Date: 2021/10/29 15:16
 * @Description: 用户类型处理
 */
@Component
public class UserTypeContext implements ApplicationContextAware {
    private static final String NO_USER_TYPE_MSG = "该用户类型没有对应策略";

    private static Map<String, Class<? extends UserPayService>> userPayBeanMap = new HashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 将实现 有UserType 注解，实现UserPayService 接口的类放到userPayBeanMap
     * @param applicationContext 上下文
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> userTypeMap = applicationContext.getBeansWithAnnotation(UserType.class);
        userTypeMap.forEach((k,v)->{
            if(v instanceof UserPayService){
                Class<? extends UserPayService> payServiceClass = ((UserPayService) v).getClass();
                userPayBeanMap.put(String.valueOf(payServiceClass.getAnnotation(UserType.class).value()), payServiceClass);
            }
        });
    }

    /**
     * 通过用户类型
     * @param userType 用户类型
     * @return  用户类型实现类
     */
    public UserPayService getUserService(UserTypeEnum userType) {
        String userTypeStr = userType.toString();
        Class<? extends UserPayService> userPayClass = userPayBeanMap.get(userTypeStr);
        if (Objects.isNull(userPayClass)) {
            throw new IllegalArgumentException(NO_USER_TYPE_MSG);
        }
        return applicationContext.getBean(userPayClass);
    }
}
